<?php
declare (strict_types = 1);

namespace app\command;

use app\common\order\model\OrderCollect;
use app\common\third\Message;
use app\common\third\Wechat;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;

class Notice extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('notice')
            ->addOption('type', null, Option::VALUE_REQUIRED, 'the customer allocate notice')
            ->setDescription('the notice command');        
    }

    protected function execute(Input $input, Output $output)
    {
    	// 指令输出
    	$output->writeln('notice');
        $type = $input->getOption('type');
        switch ($type) {
            // 客户分配通知
            case 'customerAllocate':
                $this->customer_allocate();
                break;

            // 收款提醒
            case 'makeCollection':
                $this->make_collection();
                break;
        }
    }

    /**
     * 客户分配通知
     */
    public function customer_allocate()
    {
        $Wechat = new Wechat();
        $Message = new Message();
        $userLogic = new \app\common\system\logic\UserLogic();
        // 获取队列名称
        $queueName = $Message->getCustomerAllocateQueue();
        foreach ($queueName as $key=>$value) {
            $row = json_decode($value, true);

            $toUser = $userLogic->getUser($row['toUser'], ['id', 'realname', 'work_wechat']);
            if (empty($toUser['work_wechat'])) continue;
            $rs = $Wechat->send_text_message($toUser['work_wechat'], $row['content']);
            // 如果发送成功
            if ($rs['errcode'] == 0) {
                // 从队列中删除
                $Message->delCustomerAllocateQueue($value);
            }
        }
    }

    /**
     * 收款提醒
     */
    public function make_collection()
    {
        $where = [];
        $where[] = ['complete', '<', 100];
        // 今日凌晨的时间戳
        $today = strtotime(date('Y-m-d'));
        // $where[] = ['collected_time', '=', $today];

        $model = new OrderCollect();
        // 使用hasOne关联查询 order
        $collects =  $model->where($where)->select();
        $Wechat = new Wechat();
        foreach ($collects as $collect) {
            $order = $collect->order;
            $user = $order->user;
            $content = "【收款提醒】\n客户：{$order['bridegroom']}\n订单：{$order['order_no']}\n金额：{$collect['price']}元\n收款时间：{$collect['collected_time']}\n收款进度：{$collect['complete']}%";
            if (empty($user['work_wechat'])) continue;
            $rs = $Wechat->send_text_message($user['work_wechat'], $content);
        }
    }

}
